package com.caishi.lkx.handler;

// PkTypeHandler.java

import com.caishi.lkx.exam.ienum.type.PkType;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PkTypeHandler extends BaseTypeHandler<PkType> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, PkType parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.name());
    }

    @Override
    public PkType getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (value != null) {
            try {
                return PkType.valueOf(value);
            } catch (IllegalArgumentException e) {
                // 处理无效的枚举值
                throw new SQLException("Unknown enum value: " + value);
            }
        }
        return null;
    }

    @Override
    public PkType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (value != null) {
            try {
                return PkType.valueOf(value);
            } catch (IllegalArgumentException e) {
                throw new SQLException("Unknown enum value: " + value);
            }
        }
        return null;
    }

    @Override
    public PkType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (value != null) {
            try {
                return PkType.valueOf(value);
            } catch (IllegalArgumentException e) {
                throw new SQLException("Unknown enum value: " + value);
            }
        }
        return null;
    }
}
